import  pickle
import os
import random
from .card import Card
from .user import User
from .log import Log
#主要操作类，（所有的功能都在这个类中去实现）
class Operation():
    users={}#存储所有用户
    usersid={}
    login_status=False
    userobj=None
    def __init__(self):
        if os.path.exists('./databases/user.txt'):
            with open('./databases/user.txt','rb') as fp:
                self.users=pickle.load(fp)
                for k,v in self.users.items():
                    self.usersid[v.userid]=k
        else:
            self.users={}
        print(self.users,self.usersid)
    def login(self):
        print('登录')
        self.userobj = self.get_card_info()
        cardobj = self.userobj.card
        if self.check_pwd(cardobj):
            yz=self.yanzheng()
            print('验证码为：%s'%yz)
            while True:
                re_yz=input('请输入验证码：')
                if re_yz==yz:
                    self.login_status=True
                    print(f'恭喜您，{self.userobj.username},登录成功')
                    print('现在可以进行其他操作了！！！')
                    return self.userobj
                else:
                    print('验证码输入错误，请重新输入！！！')
        else:
            print('登录失败！！！')
            return self.login()
    #退出并保存0
    def save(self):
        with open('./databases/user.txt','wb') as fp:
            pickle.dump(self.users,fp)
        with open('./databases/usersid.txt','wb') as f:
            pickle.dump(self.usersid,f)
    #注册1
    def register(self):
        username=self.get_username()
        userid = self.get_userid()
        phone = self.get_phone()
        password=self.get_pwd()
        print(username,userid,phone,password)
        #开卡
        cardid=self.get_cardid()
        print(cardid)
        #创建卡
        cardobj=Card(cardid,password)
        userobj=User(username,userid,phone,cardobj)
        print(cardobj,userobj)
        self.users[cardid]=userobj
        print(f'恭喜你，{username}开卡成功，账号为：{cardid},余额为:10元')
    #查询2
    def query(self):
            if self.login_status:
                cardobj = self.userobj.card
                num = input('按1确认查询余额，  按2确认查询交易记录,   其他返回:  ')
                if num=='1':
                    print(f'您的卡号：{cardobj.cardid},余额为：{cardobj.money}元')
                elif num=='2':
                    username=self.userobj.username
                    with open(f'./databases/{username}.txt','r') as fp:
                        print(fp.read())
                else:
                    print('输入的金额有误，请重新输入')
                return
            else:
                print('请先登录再进行其他操作！！！')
                return self.login()

    #存钱3
    def save_money(self):
        print(self.login_status)
        if self.login_status:
            print(f'存款账户为：{self.userobj.username}')
            num=input('按1确认存款，其他返回:  ')
            if num=='1':
                while True:
                    m=input('输入存款金额:')
                    if m.isdigit():
                        self.userobj.card.money+=int(m)
                        print(f'本次存入{m}元,您的余额为：{self.userobj.card.money}元')
                        lo=Log(self.userobj)
                        lo.sav_m(self.userobj,m)
                        return
                    else:
                        print('输入的金额有误，请重新输入')
        else:
            print('请先登录再进行其他操作！！！')
            self.login()


    #取钱4  mm
    def get_money(self):
        if self.login_status:
            cardobj = self.userobj.card
            print(f'取款账户为：{self.userobj.username}')
            num = input('按1确认取款，其他返回:  ')
            if num == '1':
                while True:
                    m = input('输入取款金额:')
                    if m.isdigit():
                        cardobj.money -= int(m)
                        print(f'本次取出{m}元,您的余额为：{cardobj.money}元')
                        lo = Log(self.userobj)
                        lo.get_m(self.userobj, m)
                        return
                    else:
                        print('输入的金额有误，请重新输入')
        else:
            print('请先登录再进行其他操作！！！')
            self.login()
    #转账5
    def trans_money(self):
        if self.login_status:
            cardobj = self.userobj.card
            while True:
                tran_cardid=input('请输入要转入的卡号：')
                if tran_cardid in self.users.keys():
                    if self.users[tran_cardid].card.islock:
                        print('当前卡已被锁定，请选择其他卡进行转账！！！')
                    else:
                        print(f'您当前的账户余额为{cardobj.money}')
                        while True:
                            m=input('请输入您要转的金额：')
                            if int(m)<=cardobj.money:
                                cardobj.money-=int(m)
                                self.users[tran_cardid].card.money+= int(m)
                                reuserobj=self.users[tran_cardid]
                                print(f'卡号为：{cardobj.cardid}的余额为：{cardobj.money}元')
                                print(f'卡号为：{tran_cardid}的余额为：{self.users[tran_cardid].card.money}元')
                                print(f'恭喜您{cardobj.cardid}，转账成功！！！')
                                lo = Log(self.userobj)
                                lo.trans_m(self.userobj,reuserobj, m)
                                return
                            else:
                                print('您要转的金额大于您的余额,请重新输入!!! ')
        else:
            print('请先登录再进行其他操作！！！')
            self.login()
    #改密6
    def change_pwd(self):
        if self.login_status:
            cardobj = self.userobj.card
            num = input('请选择：按1原密码改密，按2身份证改密，其他返回:  ')
            if num == '1':
                if self.check_pwd(cardobj):
                    cardobj.password=self.get_pwd()
                    print('恭喜您，修改成功！！！')
                    return
            else:
                userid=input('请输入您的身份证号：')
                if userid:
                    if userid==self.userobj.userid:
                        cardobj.password = self.get_pwd()
                        print('恭喜您，修改成功！！！')
                else:
                    print('身份证号不能为空')
        else:
            print('请先登录再进行其他操作！！！')
            self.login()






    #锁卡7
    def lock(self):
        if self.login_status:
            cardobj = self.userobj.card
            num = input('请选择：按1密码冻结，按2身份证冻结，其他返回:  ')
            if num == '1':
                if self.check_pwd(cardobj):
                    cardobj.islock = True
                    print('恭喜您，冻结成功！！！')
                    return
            else:
                userid = input('请输入您的身份证号：')
                if userid:
                    if userid == self.userobj.userid:
                        cardobj.islock = True
                        print('恭喜您，冻结成功！！！')
                        return
                else:
                    print('身份证号不能为空')
        else:
            print('请先登录再进行其他操作！！！')
            self.login()
    #解卡8
    def unlock(self):
        print('现在可以解锁卡号了')
        cardid = input('请输入您的卡号：')
        if cardid not in self.users.keys():
            print('当前卡不存在')
            return
        if not(self.users[cardid].card.islock):
            print('当前卡不用解锁')
            return
        userid = input('请输入您的身份证号：')
        if userid:
            if userid == self.users[cardid].userid:
                self.users[cardid].card.islock = False
                print('恭喜您，解冻成功！！！')
                return
            else:
                print('身份证号不存在，请重新输入！！！')
        else:
            print('身份证号不能为空')
    #补卡9
    def new_card(self):
        userid = input('请输入您的身份证号：')
        if userid in self.usersid.keys():
            if self.users[self.usersid[userid]].card.islock:
                print('该卡已被冻结')
                return
            else:
                userobj=self.users[self.usersid[userid]]
                self.users.pop(self.usersid[userid])
                self.usersid.pop(userid)
                cardid=self.get_cardid()
                self.usersid[userid]=cardid
                self.users[cardid]=userobj
                print('补卡已成功')
                print(f'恭喜您：{userobj.username}，补卡成功，新卡号为：{cardid},余额为：{userobj.card.money}')
                return
        else:
            print('该身份证号不存在')


    def get_pwd(self):
        while True:
            pwd=input('请输入密码：')
            if pwd!=' ':
                repwd = input('请输入确认密码：')
                if pwd!=repwd:
                    print('两次密码输入不一致')
                else:
                    return pwd
            else:
                print('密码不能为空')
    def get_cardid(self):
        #得到最大的卡号
       try:
            maxcard_id=max(self.users.keys())
       except:
            maxcard_id='000000'
       cardid=str(int(maxcard_id)+1).zfill(6)
       return cardid
    #检测用户输入的密码，接收卡对象，用于检测用户输入的是否正确
    def check_pwd(self,cardobj):
        num=3
        while True:
            pwd=input('请输入您的密码：')
            if pwd==cardobj.password:
                return True
            else:
                num-=1
                if num==0:
                    cardobj.islock=True
                    print('密码错误三次，您的卡已经被锁定')
                    return False
                else:
                    print(f'密码输入错误，{num}次机会')
    def get_userid(self):
            userid=input('请输入您的身份证号：')
            if userid:
                if userid.isdigit() and len(userid)==6:
                    if userid not in self.usersid.keys():
                        return userid
                    else:
                        print('用户已存在！！！')
                        return self.get_userid()
                else:
                    print('您输入的身份证号不合法！！！')
                    return self.get_userid()
            else:
                print('身份证号不能为空')
                return self.get_userid()
    def get_username(self):
        while True:
            username=input('请输入您的用户名：')
            if username:
                if username.isalpha():
                    return username
                else:
                    print('您输入的身份证号不合法！！！')
            else:
                print('身份证号不能为空')
    def get_phone(self):
        while True:
            phone=input('请输入您的手机号：')
            if phone:
                if phone.isdigit() and len(phone)==11:
                        return phone
                else:
                    print('您输入的手机号不合法！！！')
            else:
                print('手机号不能为空')
    def get_card_info(self):
        cardid = input('请输入您的卡号：')
        if cardid:
            if cardid  in self.users.keys():
                if not(self.users[cardid].card.islock):
                    userobj=self.users[cardid]
                    return userobj
                else:
                    print('当前卡已被锁定，请重新输入！！！')
                    return self.get_card_info()
            else:
                print('当前卡不存在，请重新输入！！！')
                return self.get_card_info()
        else:
            print('卡号不能为空，请重新输入！！！')
            return self.get_card_info()

    def yanzheng(self):
        string = ''
        for i in range(4):  # 设置验证码位数
            num = random.randint(0, 61)  # 一共有62种可能的情况
            if num < 10:
                string += str(num)
            elif 10 <= num <= 35:
                string += chr(num + 55)  # 随机产生A-Z
            else:
                string += chr(num + 61)  # 随机产生a-z
        return string


